/**
 *
 gcc -Wall ic.c -DDEBUGic -liconv && a utf-8 gb2312
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iconv.h>
#include <errno.h>
#define MIN(a,b) ((a)>(b)?(b):(a))
void dumprawmsg(const char *p, int len)
{
	int i = 0;
	for(i = 0; i < len; i++)
	{
		unsigned char c = p[i];
		printf("%.2X ", c);
	}
	printf ("\n");
}
int convmsg(char * src, char * des, int srclen, int deslen, const char *srctype,const char *destype)
{
	if (strcmp(srctype, destype) == 0)
	{
		memcpy(des, src, MIN(srclen, deslen));
		return 0;
	}
	iconv_t conv = iconv_open (destype, srctype);
	if(conv == (iconv_t)-1)
	{
		printf("iconv open err\n");
		return -1;
	}
	size_t  avail = deslen;
	size_t insize = srclen;
	char *wrptr = des;
	char *inptr = src;
	while (avail > 0)
	{
		size_t nconv;
		printf("avail:%d\n", avail);
		/* Do the conversion.  */
		nconv = iconv (conv, (const char**)&inptr, &insize, &wrptr, &avail);
		printf("\n%d\n",nconv);
		if (nconv == (size_t) -1)
		{
			/* Not everything went right.  It might only be
			   an unfinished byte sequence at the end of the
			   buffer.  Or it is a real problem.  */
			if (errno == EINVAL)
			{
				/* This is harmless.  Simply move the unused
				   bytes to the beginning of the buffer so that
				   they can be used in the next round.  */
				//memmove (inbuf, inptr, insize);
				printf("EINVAL\n");
			}
			else
			{
				/* It is a real problem.  Maybe we ran out of
				   space in the output buffer or we have invalid
				   input.  In any case back the file pointer to
				   the position of the last processed byte.  */
				printf("error\n");
				break;
			}
		}else if(nconv == 0){
			break;
		}else {
			printf("------------error\n");
			break;
		}
	}
	iconv_close (conv);
	return 0;
}

char*my_iconv(const char * src,const char*frometype,const char * totype)
{
	int srclen = strlen(src)+1;
	int deslen = srclen*4;
	char* des = malloc(deslen);
	memset(des,0,deslen);
	printf("%s -> %s\n", frometype, totype);
	/*dumprawmsg(des, 400);*/
	convmsg((char*)src, (char*)des, srclen, deslen, frometype, totype);
	return des;
}
#ifdef DEBUGic
int main(int argc, char * argv[])
{
	if (argc < 3)
	{
		printf("need two type para\n");
		return -1;
	}

	char *src = "abcd 1234 其他";
	char *des = my_iconv(src,argv[1],argv[2]);
	/*dumprawmsg((const char*)des, 400);*/
	printf("des is : %s\n", des);
	free(des);
	return 0;
}
#endif
